def limit_list_d(start_date)
  $TusharePro.tushare_pro("limit_list_d", "limit_type": "U", "start_date": start_date, "end_date": Time.now.strftime("%Y%m%d"))
end
def limit_count(code)
  $TusharePro.tushare_pro("limit_list_d", "ts_code": to_ths_code(code), "limit_type": "U", "start_date": (Time.now - 365.day).strftime("%Y%m%d"), "end_date": Time.now.strftime("%Y%m%d")).count
end
# code 格式： 600011
# 有限频，控制调用频率
def today_volume(code)
  sse = $TusharePro.tushare_pro("trade_cal", "exchange": "SSE", "start_date": (Time.now - 10.day).strftime("%Y%m%d"), "end_date": (Time.now).strftime("%Y%m%d")).select { |sse| sse["is_open"] == 1 }
  today_trade_date, yesterday_trade_date = sse.first(1).last["cal_date"], sse.first(1).last["pretrade_date"]
  today, yesterday = "#{today_trade_date[0, 4]}-#{today_trade_date[4, 2]}-#{today_trade_date[6, 2]}", "#{yesterday_trade_date[0, 4]}-#{yesterday_trade_date[4, 2]}-#{yesterday_trade_date[6, 2]}"
  delay_millisecond(1, 50){}
  kline = RealTime.kline to_sina_code(code), 5, 3, 500
  today_5min = kline.select { |x| x["day"].split(" ")[0] == today }
  yesterday_5min = kline.select { |x| x["day"].split(" ")[0] == yesterday }.first(today_5min.count)
  today_volume = today_5min.pluck("volume").sum { |x| x.to_f }
  yes_volume = yesterday_5min.pluck("volume").sum { |x| x.to_f }
  (today_volume / yes_volume).round(2) if yes_volume != 0
end

# 一些公用的小方法
# 往前 x 个交易日是哪天
def trade_date(x)
  days = x < 10 ? x + 20 : x * 2.3
  sse = $TusharePro.tushare_pro("trade_cal", "exchange": "SSE", "start_date": (Time.now - days.day).strftime("%Y%m%d"), "end_date": (Time.now).strftime("%Y%m%d")).select { |sse| sse["is_open"] == 1 }
  sse[x - 1]["cal_date"]
end
def last_trade_date
  $TusharePro.tushare_pro("trade_cal", "exchange": "SSE", "start_date": (Time.now - 10.day).strftime("%Y%m%d"), "end_date": (Time.now).strftime("%Y%m%d")).select { |sse| sse["is_open"] == 1 }.first
end
def trade_time
  Time.current.between?(Time.current.change(hour: 9, min: 15), Time.current.change(hour: 11, min: 31)) || Time.current.between?(Time.current.change(hour: 13, min: 00), Time.current.change(hour: 15, min: 01))
end

def to_sina_code(code)
  return %w(5 6 9).include?(code.to_s[0]) ? "sh#{code}" : "sz#{code}" if code.size == 6
  return code[-2..-1].downcase + code[0..5] if code[6] == "."
  code if code[0..1] == "sh" || code[0..1] == "sz"
end

def to_ths_code(code)
  return %w(5 6 9).include?(code.to_s[0]) ? "#{code}.SH" : "#{code}.SZ" if code.size == 6
  return code[0..5] + code[0..1].upcase if code[0..1] == "sh" || code[0..1] == "sz"
  code if code[6] == "."
end

def cul_change(open, close)
  ((close.to_f - open.to_f) * 100 / open.to_f).round(2)
end

def auto_p_color_n(num)
  return "\e[31m#{num}\e[0m" if num > 0
  return "\e[36m#{num}\e[0m" if num > 7
  "\e[35m#{num}\e[0m"
end